Lesson 9 - python lists
It is always important to remember that lists are much more powerful than arrays. For example to reverse the items in an array would take a loop and some swapping code. With a list you simply say myList.reverse()! When writing exam questions it is always important to remember that you will not be able to use these helper functions.
Lists use the symbol [] to represent themselves. This is very similar to arrays in c++ or java. To create a list you can specify what items you want to add by listing them out. The code below shows a few examples. The last example shows how to create a multi-dimensional list. You can create lists within lists just as easily as you can create a normal list.
list = [6, 3 , 1, 9]
nameList = ["bert", "fred", "sally"]
emptyList = []
nestedLists = [ [ "fred", "sally"], [1, 3] ]
To access a value inside a list you can use it's index. The first element is accessed by i[0], second i[1] and so on. If you try and access a index which does not exist then a error will occur. You can also use a for loop to iterate over all values. You can change values using the exact same method you would use to assign values to normal variables
nameList = ["bert", "fred", "sally"]
for z in nameList:
print z
z[1] = "john"
for z in nameList:
print z # should print bert, john, sally!
Lists have some methods which are very useful. Some of the main ones are shown below -
- list.append(x) - Adds a item to a list
- list.remove(x) - removes a item from a list (does a search for it!)
- list.reverse() - reverses all items in a list
- list.count() - Finds the number of items in the list
nameList = ["bert", "fred", "sally"]
nameList.append("john")
nameList.append("sue")
nameList.remove("fred")
nameList.reverse()
print "number in the list", nameList.count()
# should print sue, john, sally, bert
for z in nameList:
print z